package com.smarttest.portal.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.g7s.test.utils.Excel.DataHandlers;
import com.g7s.test.utils.common.CommonUtils;
import com.smarttest.common.beans.GeneralResultWithStatus;
import com.smarttest.common.beans.Result;
import com.smarttest.common.beans.TestResult;
import com.smarttest.common.util.InterfaceUtils;
import com.smarttest.common.util.MsgSend;
import com.smarttest.common.util.ThreadPoolHandler;
import com.smarttest.portal.mapper.DbAutoDetailsExcresultMapper;
import com.smarttest.portal.mapper.DbAutoEnvironmentMapper;
import com.smarttest.portal.mapper.DbAutoInterfacescenedetailsMapper;
import com.smarttest.portal.mapper.DbAutoInterfacesummaryMapper;
import com.smarttest.portal.mapper.DbAutoReleaseMapper;
import com.smarttest.portal.mapper.DbAutoSummaryExcresultMapper;
import com.smarttest.portal.mapper.DbAutoTesturlMapper;
import com.smarttest.portal.mapper.DbAutoTimertaskMapper;
import com.smarttest.portal.mapper.SuperManagerMapper;
import com.smarttest.portal.pojo.DbAutoDetailsExcresultWithBLOBs;
import com.smarttest.portal.pojo.DbAutoEnvironmentExample;
import com.smarttest.portal.pojo.DbAutoInterfacescenedetailsExample;
import com.smarttest.portal.pojo.DbAutoInterfacescenedetailsExample.Criteria;
import com.smarttest.portal.pojo.DbAutoInterfacescenedetailsWithBLOBs;
import com.smarttest.portal.pojo.DbAutoInterfacesummaryExample;
import com.smarttest.portal.pojo.DbAutoInterfacesummaryWithBLOBs;
import com.smarttest.portal.pojo.DbAutoRelease;
import com.smarttest.portal.pojo.DbAutoSetting;
import com.smarttest.portal.pojo.DbAutoSettingExample;
import com.smarttest.portal.pojo.DbAutoSummaryExcresult;
import com.smarttest.portal.pojo.DbAutoTesturl;
import com.smarttest.portal.pojo.DbAutoTimertaskExample;
import com.smarttest.portal.pojo.DbAutoTimertaskWithBLOBs;
import com.smarttest.portal.service.Autog7Service;

@Service
public class Autog7ServiceImpl implements Autog7Service {
	@Autowired
	DbAutoInterfacescenedetailsMapper dbAutoInterfacescenedetailsMapper;
	@Autowired
	DbAutoInterfacesummaryMapper dbAutoInterfacesummaryMapper;
	@Autowired
	DbAutoTesturlMapper dbAutoTesturlMapper;
	@Autowired
	DbAutoSummaryExcresultMapper DbAutoSummaryExcresultMapper;
	@Autowired
	DbAutoDetailsExcresultMapper DbAutoDetailsExcresultMapper;
	@Autowired
	DbAutoTimertaskMapper DbAutoTimertaskMapper;
	@Autowired
	DbAutoReleaseMapper DbAutoReleaseMapper;
	@Autowired
	DbAutoEnvironmentMapper DbAutoEnvironmentMapper;
	@Autowired
	SuperManagerMapper SuperManagerMapper;
	@Autowired
	com.smarttest.portal.mapper.DbAutoSettingMapper DbAutoSettingMapper;
	@Override 
	public String getDetailsIds(int sid) {
		DbAutoInterfacescenedetailsExample example = new DbAutoInterfacescenedetailsExample();
		Criteria criteria = example.createCriteria();
		criteria.andIntersumidEqualTo(sid);
		List<DbAutoInterfacescenedetailsWithBLOBs> dblist = dbAutoInterfacescenedetailsMapper
				.selectByExampleWithBLOBs(example);
		String ids = "";
		for (DbAutoInterfacescenedetailsWithBLOBs dbs : dblist) {
			if (!ids.equals("")) {
				ids += ",";
			}
			ids += dbs.getId();
		}
		return ids;
	}

	@Override
	public JSONObject getTestIds(String env, String modules, String internames, String testers, String degrees,
			int level) {
		List<String> moduleslist = null;
		List<String> interfaces = null;
		List<String> importants = null;
		List<String> owners = null;
		if (!CommonUtils.isStrEmpty(modules)) {
			moduleslist = Arrays.asList(modules.split(","));
		}
		if (!CommonUtils.isStrEmpty(internames)) {
			interfaces = Arrays.asList(internames.split(","));
		}
		if (!CommonUtils.isStrEmpty(testers)) {
			importants = Arrays.asList(testers.split(","));
		}
		if (!CommonUtils.isStrEmpty(degrees)) {
			owners = Arrays.asList(degrees.split(","));
		}
		JSONObject testids = new JSONObject();
		List<DbAutoInterfacesummaryWithBLOBs> lsum = dbAutoInterfacesummaryMapper.selectByConcat(env, moduleslist,
				interfaces, importants, owners);
		for (DbAutoInterfacesummaryWithBLOBs sum : lsum) {
			int sumid = sum.getId();
			DbAutoInterfacescenedetailsExample example = new DbAutoInterfacescenedetailsExample();
			example.createCriteria().andIntersumidEqualTo(sumid);
			List<DbAutoInterfacescenedetailsWithBLOBs> detailidlist = dbAutoInterfacescenedetailsMapper
					.selectByExampleWithBLOBs(example);
			String ids = "";
			for2:
			for (DbAutoInterfacescenedetailsWithBLOBs dbs : detailidlist) {
				if (level != -1 && dbs.getLevel() != level) {
					continue for2;
				}
				if (!ids.equals("")) {
					ids += ",";
				}
				ids += dbs.getId();
			}
			testids.put(String.valueOf(sumid), ids);
		}
		return testids;
	}
	@Transactional
	@Override
	public GeneralResultWithStatus runTest(JSONObject testids,int releaseid) {	
		ThreadPoolExecutor threadpool = ThreadPoolHandler.getThreadpool();
		//采用线程池多线程并发批量执行用例
		Map<String, Map<String, TestResult>> summap = new HashMap<String, Map<String, TestResult>>();
		final Map<String, Boolean> m = new HashMap<>();
		m.put("result", true);
		for (String key : testids.keySet()) {
			final Map<String, TestResult> detailmap = new HashMap<String, TestResult>();
			final String detailidsarr[] = testids.getString(key).split(",");
			final int sumresultid = insertSumResult(Integer.parseInt(key), releaseid);
			String issuc = "";
			final List<Integer> tlist = new ArrayList<Integer>();
			tlist.add(0, 1);
			Runnable r = new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					for (String detailid : detailidsarr) {
						TestResult t = runTest(Integer.parseInt(detailid),sumresultid);
						if (t.getResult().equalsIgnoreCase(Result.FAIL)) {
							m.put("result", false);
							tlist.set(0, tlist.get(0) * 0);
						}
						else if (t.getResult().equalsIgnoreCase(Result.SKIP)) {
							tlist.set(0, tlist.get(0) * 2);
						}
						else if (t.getResult().equalsIgnoreCase(Result.PASS)) {
							tlist.set(0, tlist.get(0) * 1);
						}
						detailmap.put(detailid, t);
					}
				}
			};
//			threadpool.execute(r);
			Future<?> f = threadpool.submit(r);
			while (true) {
				if (f.isDone()) {
					summap.put(key, detailmap);
					int tmpint = tlist.get(0);
					int lastresult = 0;
					if (tmpint == 0) {
						issuc = "FAIL";
						lastresult = 1;
					}
					else if (tmpint%2 ==0) {
						issuc = "SKIP";
						lastresult = 2;
					}
					else if (tmpint == 1) {
						issuc = "PASS";
						lastresult = 0;
					}
					updateSumResult(Integer.parseInt(key), sumresultid, lastresult, new Date(), issuc);
					break;
				}			
			}
		}
		if (m.get("result")) {
			return GeneralResultWithStatus.error("本次测试未完全通过", summap);
		} else {
			return GeneralResultWithStatus.okData(null, summap);
		}
	}
	@Transactional
	@Override
	public int createNewRelease(int envid, String name, String testids) {
		DbAutoRelease record = new DbAutoRelease();
		record.setEnvid(envid);
		record.setName(name);
		record.setTestids(testids);
		int count = DbAutoReleaseMapper.insertAndGetId(record);
		if (count > 0) {
			return record.getId();
		}
		else {
			return -1;
		}
	}
	@Transactional
	@Override
	public int insertSumResult(int sumid,int releaseid) {
		DbAutoSummaryExcresult sumresult = new DbAutoSummaryExcresult();
		sumresult.setSumid(sumid);
		if (releaseid > 0) {
			sumresult.setReleaseid(releaseid);
		}
		sumresult.setUsetimemsec(0l);
		sumresult.setExctime(new Date());
		int count = DbAutoSummaryExcresultMapper.insertAndGetId(sumresult);
		if (count > 0) {
			return sumresult.getId();
		}
		else {
			return -1;
		}
	}
	@Transactional
	@Override
	public TestResult runTest(int detailid,int sumresultid) {
		// TODO Auto-generated method stub
		DbAutoInterfacescenedetailsExample example = new DbAutoInterfacescenedetailsExample();
		Criteria criteria = example.createCriteria();
		criteria.andIdEqualTo(detailid);
		DbAutoInterfacescenedetailsWithBLOBs dbs = dbAutoInterfacescenedetailsMapper.selectByExampleWithBLOBs(example)
				.get(0);
		int sumid = dbs.getIntersumid();
		DbAutoInterfacesummaryExample example2 = new DbAutoInterfacesummaryExample();
		com.smarttest.portal.pojo.DbAutoInterfacesummaryExample.Criteria criteria2 = example2.createCriteria();
		criteria2.andIdEqualTo(sumid);
		DbAutoInterfacesummaryWithBLOBs dbsum = dbAutoInterfacesummaryMapper.selectByExampleWithBLOBs(example2).get(0);
		String testdata = dbs.getInnerparams();
		int apiurlid = dbsum.getApiurlid();
		DbAutoTesturl testurl = dbAutoTesturlMapper.selectByPrimaryKey(apiurlid);
		Map<String, Object> m = JSON.parseObject(dbsum.getOuterparams());
		if (dbsum.getInnerparamToOuter()) {
			m.putAll(JSON.parseObject(testdata));
		}
		Map<String, String> newMap = new HashMap<String, String>();
		for (Map.Entry<String, Object> entry : m.entrySet()) {
			newMap.put(entry.getKey(), entry.getValue().toString().replaceAll("\\$\\{jsonParams\\}", testdata));
		}
		DbAutoDetailsExcresultWithBLOBs record = new DbAutoDetailsExcresultWithBLOBs();
		record.setDetailid(detailid);
		record.setSumid(sumid);
		long time1 = System.currentTimeMillis();
		//调用接口测试
		TestResult tr = InterfaceUtils.interfaceTest(testurl.getUrl(), dbsum.getRequesttype(), newMap, testdata,
				dbs.getExpectcode(), dbs.getExpectmsg(), dbs.getResultasserts(), dbs.getExpectcount());
		long time2 = System.currentTimeMillis();
		record.setUsetimemsec(time2 - time1);
		if (sumresultid > 0) {
			record.setSumresultid(sumresultid);
			DbAutoSummaryExcresult sumresult = DbAutoSummaryExcresultMapper.selectByPrimaryKey(sumresultid);
			long timesecs = sumresult.getUsetimemsec();
			sumresult.setUsetimemsec(timesecs + (time2 - time1));
			DbAutoSummaryExcresultMapper.updateByPrimaryKeySelective(sumresult);
		}
		record.setResult(tr.getResult());
		record.setReturns(tr.getReturns());
		record.setException(tr.getErrmsg());
		record.setExctime(new Date());
		DbAutoDetailsExcresultMapper.insert(record);
		return tr;
	}
	
	@Override
	public TestResult debugTest(String apiurl, String httpmethod, JSONObject outerparams, Boolean dataAsParams, 
			JSONObject datas) {
		// TODO Auto-generated method stub
		Map<String, Object> m = outerparams;
		if (dataAsParams) {
			m.putAll(datas.getJSONObject("testdata"));
		}
		Map<String, String> newMap = new HashMap<String, String>();
		for (Map.Entry<String, Object> entry : m.entrySet()) {
			//${jsonParams} 代表json格式的入参
			newMap.put(entry.getKey(),
					entry.getValue().toString().replaceAll("\\$\\{jsonParams\\}", datas.getString("testdata")));
		}
		TestResult tr = InterfaceUtils.interfaceTest(apiurl, httpmethod, newMap, datas.getString("testdata"),
				datas.getString("expectcode"), datas.getString("expectmessage"), datas.getString("assertresult"),
				datas.getString("expectnum"));
		return tr;
	}

	@Override
	public HashMap<String, Object> getTimerTaskList(String describing, int pageIndex, int pageSize, String sortField,
			String sortOrder) {
		DbAutoTimertaskExample example = new DbAutoTimertaskExample();
		String orderByClause = "";
		HashMap<String, Object> m = new HashMap<String, Object>();
		if (!sortField.equals("")) {
			if ("desc".equals(sortOrder) == false)
				sortOrder = "asc";
			orderByClause += sortField + " " + sortOrder;
		} else {
			orderByClause += "createtime desc";
		}
		example.setOrderByClause(orderByClause);
		com.smarttest.portal.pojo.DbAutoTimertaskExample.Criteria c = example.createCriteria();
		if (null != describing && !describing.trim().isEmpty()) {
			c.andDescribingLike(describing);
		}
		String sql = "SELECT t1.*,t2.`name` as envname FROM `db_auto_timertask` t1 join db_auto_environment t2 on t1.envid = t2.id ;";
		List<LinkedHashMap<String, Object>> l = SuperManagerMapper.superManagerSelect(sql);
//		List<DbAutoTimertaskWithBLOBs> l = DbAutoTimertaskMapper.selectByExampleWithBLOBs(example);
		int start = pageIndex * pageSize, end = start + pageSize;
		List<LinkedHashMap<String, Object>> ls = new ArrayList<LinkedHashMap<String, Object>>();
		for (int i = 0; i < l.size(); i++) {
			LinkedHashMap<String, Object> task = l.get(i);
			if (task.isEmpty())
			{
				continue;
			}
			int releaseId = Integer.parseInt(task.get("releaseid").toString());
			if (releaseId > 0) {
				task.put("releasename", getReleaseName(releaseId));
			}
			else {
				task.put("releasename", "");
			}
			if (start <= i && i < end) {
				ls.add(task);
			}
		}
		m.put("data", ls);
		m.put("total", l.size());
		return m;
	}

	@Transactional
	@Override
	public int updateTimerTaskList(JSONArray JA) {
		String operating, runtime;
		int id, exctype, count = 0;
		for (Object o : JA) {
			operating = ((JSONObject) o).getString("_state");
			runtime = ((JSONObject) o).getString("runtime");
			runtime = runtime.substring(runtime.length() - 8, runtime.length());
			exctype = ((JSONObject) o).getIntValue("exctype");
			id = ((JSONObject) o).getIntValue("id");
			// java6不支持switch string
			if (operating.equalsIgnoreCase("modified")) {
				DbAutoTimertaskWithBLOBs task = DbAutoTimertaskMapper.selectByPrimaryKey(id);
				task.setExctype(exctype);
				task.setRuntime(runtime);
				count += DbAutoTimertaskMapper.updateByPrimaryKeySelective(task);
			} else if (operating.equalsIgnoreCase("removed")) {
				count += DbAutoTimertaskMapper.deleteByPrimaryKey(id);
			}
		}
		return count;
	}
	@Transactional
	@Override
	public int deleteCases(List<Integer> ids) throws Exception{
		// TODO Auto-generated method stub
		int resultReturn = 0;
		DbAutoInterfacescenedetailsExample example = new DbAutoInterfacescenedetailsExample();
		try{
		for (Integer each : ids) {
			int result = dbAutoInterfacesummaryMapper.batchDelete(ids);
			resultReturn+=result;
		}
		}catch(Exception e){
			throw e;
		}
		return resultReturn;
	}
	@Transactional
	@Override
	public int updateSumResult(Integer sumid,Integer sumresultid, int lastresult, Date lastruntime,String result) {
		DbAutoInterfacesummaryWithBLOBs blob = dbAutoInterfacesummaryMapper.selectByPrimaryKey(sumid);
		blob.setLastresult(lastresult);
		blob.setLastruntime(lastruntime);
		DbAutoSummaryExcresult d = DbAutoSummaryExcresultMapper.selectByPrimaryKey(sumresultid);
		d.setResult(result);
		DbAutoSummaryExcresultMapper.updateByPrimaryKeySelective(d);
		return dbAutoInterfacesummaryMapper.updateByPrimaryKeySelective(blob);
	}
	//该方法只适用向自动化平台导入数据时适用
	@SuppressWarnings("static-access")
	@Transactional
	@Override
	public int importCaseFromExcel(List<String> files) {
		int sumcount = 0;
		for (String file : files) {
			DataHandlers d = DataHandlers.getInstance(file);
			Workbook workbook = null;
			try {
				workbook = d.getExcelParser().getWorkBook();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				continue;
			}
			for2:
			for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
				if (workbook.getSheetAt(i).getLastRowNum() == 0){
					continue for2;
				}
				Object[][] oo = d.getData(workbook.getSheetName(i), true);
				if (!oo[1][0].toString().equalsIgnoreCase("URL") && !oo[2][0].toString().equalsIgnoreCase("httpMethod") && !oo[3][0].toString().equalsIgnoreCase("dataToJson")) {
					continue for2;
				}
				String url = oo[1][1].toString();
				String reqtype = oo[2][1].toString().toUpperCase();
				Boolean dataToJson = Boolean.valueOf(oo[3][1].toString());
				String intername = oo[5][1].toString();
				DbAutoInterfacesummaryWithBLOBs blobs = new DbAutoInterfacesummaryWithBLOBs();
				//测试URL
				blobs.setApiurlid(3);
				//重要程度
				blobs.setDegreeid(1);
				blobs.setDisabled(false);
				//测试环境
				blobs.setEnvid(3);
				blobs.setInnerparamToOuter(!dataToJson);
				//测试模块
				blobs.setModuleid(25);
				blobs.setName(intername);
				blobs.setOuterparams("{\"app_key\":\"bc7e94\",\"method\":\""+intername+"\",\"timestamp\":\"now()\",\"sign\":\"sign2(appkey,method,format,timestamp,${jsonParams},88DA9E321AF1B146B758460D5D0697F8)\",\"format\":\"json\"}");
				blobs.setRequesttype(reqtype);
				blobs.setTester("liuchi");
				Date date = new Date();
				blobs.setCreatetime(date);
				blobs.setUpdatetime(date);
				int tmpint = dbAutoInterfacesummaryMapper.insertAndGetId(blobs);
				if (tmpint > 0) {
					int sumid = blobs.getId();
					Object[][] titles = d.getData(workbook.getSheetName(i), 6, 1, 2, -1, true);
					Object[][] ooo = d.getData(workbook.getSheetName(i), 7, -1, 2, -1, true);
					for (int j = 0; j < ooo.length; j++) {
						int level = 2;
						if (!ooo[j][0].toString().isEmpty()) {
							level = Integer.parseInt(ooo[j][0].toString());
						}
						String innerparams = ooo[j][1].toString();
						String expectcode = ooo[j][2].toString();
						String expectmsg = ooo[j][3].toString();
						String expectresult = ooo[j][4].toString();
						String expectnum = ooo[j][5].toString();
						String description = ooo[j][ooo[j].length-1].toString();
						DbAutoInterfacescenedetailsWithBLOBs detailsblobs = new DbAutoInterfacescenedetailsWithBLOBs();
						detailsblobs.setInnerparams(innerparams);
						detailsblobs.setIntersumid(sumid);
						detailsblobs.setLevel(level);
						if (!expectresult.trim().isEmpty()) {
							String []resultstr = expectresult.split(";");
							JSONObject jo = new JSONObject();
							for3:
							for (int k = 0; k < resultstr.length; k++) {
								String str = resultstr[k];
								if (str.isEmpty()) {
									continue for3;
								}
								if (str.contains("(") && str.endsWith(")")) {
									str = "com.smarttest.portal.function.assertfuction.JsonCompare." + str;
								}
								else {
									str = "com.smarttest.portal.function.assertfuction.JsonCompare.containsRs(" + str + ")";
								}
								jo.put("k"+k,str);
							}
							expectresult = jo.toString();
						}					
						detailsblobs.setResultasserts(expectresult);
						detailsblobs.setDescription(description);
						detailsblobs.setExpectcode(expectcode);
						detailsblobs.setExpectcount(expectnum);
						detailsblobs.setExpectmsg(expectmsg);
						Date date2 = new Date();
						detailsblobs.setCreatetime(date2);
						detailsblobs.setUpdatetime(date2);
						dbAutoInterfacescenedetailsMapper.insert(detailsblobs);
					}
					sumcount++;
				}			
			}
		}
		return sumcount;
	}
	
	@Override
	public String getReleaseName(int releaseId) {
		return 	DbAutoReleaseMapper.selectByPrimaryKey(releaseId).getName();
	}
	@Override
	public int getEnvid(String envname) {
		DbAutoEnvironmentExample example = new DbAutoEnvironmentExample();
		com.smarttest.portal.pojo.DbAutoEnvironmentExample.Criteria  c = example.createCriteria();
		c.andNameEqualTo(envname);
		return 	DbAutoEnvironmentMapper.selectByExample(example).get(0).getId();
	}

	@Override
	public Map<Integer, Date> newTestMap() {
		// TODO Auto-generated method stub
		Map<Integer, Date> m = new HashMap<Integer, Date>();
		return m;
	}
	@Override
	public List<DbAutoSetting> getSettingBefore(int env, String modules) {
		DbAutoSettingExample example = new DbAutoSettingExample();
		com.smarttest.portal.pojo.DbAutoSettingExample.Criteria c = example.createCriteria();
		c.andEnvidEqualTo(env);
		c.andModuleidIn(JSON.parseArray(modules, Integer.class));
		c.andTypeEqualTo(0);
		return DbAutoSettingMapper.selectByExampleWithBLOBs(example);
	}
	
	@Override
	public List<DbAutoSetting> getSettingAfter(int env, String modules) {
		DbAutoSettingExample example = new DbAutoSettingExample();
		com.smarttest.portal.pojo.DbAutoSettingExample.Criteria c = example.createCriteria();
		c.andEnvidEqualTo(env);
		c.andModuleidIn(JSON.parseArray(modules, Integer.class));
		c.andTypeEqualTo(1);
		return DbAutoSettingMapper.selectByExampleWithBLOBs(example);
	}
	@Override
	public Map<Integer, Date> sendMsg(String sendmethod, String add, int port, String sendtime, String format, int internal, String msg, String startnum, String count, String key) {
		MsgSend msgsend = new MsgSend();
		List<String> msglist = Arrays.asList(msg.split(";"));
		Iterator<String> it = msglist.iterator();
		while (it.hasNext()) {
			if (it.next().isEmpty()) {
				it.remove();
			}
		}
		if (startnum.isEmpty()) {
			startnum = "1";
		}
		List<String> l2 = new ArrayList<String>();
		int tmpint = Integer.parseInt(startnum)-1;
		int tmpcount = 0;
		if (count.isEmpty() || Integer.parseInt(count) <= 0) {
			tmpcount = msglist.size() - tmpint;
		}
		else {
			tmpcount = Integer.parseInt(count);
		}
		for (int k = tmpint; k < tmpint+tmpcount; k++) {
			l2.add(msglist.get(k));
		}
		Map<Integer, Date> m = new HashMap<Integer, Date>();
		if (format.isEmpty()) {
			m = msgsend.sendMsg(add, port, l2, sendtime, "yy MM dd HH mm ss", internal);
		}
		else {
			m = msgsend.sendMsg(add, port, l2, sendtime, format, internal);
		}
		return m;
	}
	
	@Override
	public int getModuleBySumid (int sumid) {
		DbAutoInterfacesummaryExample example = new DbAutoInterfacesummaryExample();
		com.smarttest.portal.pojo.DbAutoInterfacesummaryExample.Criteria c = example.createCriteria();
		c.andIdEqualTo(sumid);
		return dbAutoInterfacesummaryMapper.selectByExample(example).get(0).getModuleid();
	}
	@Override
	public String getDatainitsBySumid (int sumid) {
		DbAutoInterfacesummaryExample example = new DbAutoInterfacesummaryExample();
		com.smarttest.portal.pojo.DbAutoInterfacesummaryExample.Criteria c = example.createCriteria();
		c.andIdEqualTo(sumid);
		return dbAutoInterfacesummaryMapper.selectByExampleWithBLOBs(example).get(0).getDatainits();
	}
	@Override
	public void initData (String datainits) {
		if (!datainits.equalsIgnoreCase("[]") && !datainits.isEmpty()){
			for (Object o : JSON.parseArray(datainits)) {
				if (((JSONObject)o).getString("type").equalsIgnoreCase("message")) {
					JSONArray ja = ((JSONObject)o).getJSONArray("data");
					 Vector<Thread> threads = new Vector<Thread>();
					 for (final Object oo : ja) {
						 Thread t = new Thread(new Runnable() {
								@Override
								public void run() {
									JSONObject jo = ((JSONObject)oo);
									String msg_sendmethod = jo.getString("msg_sendmethod");
									String msg_add = jo.getString("msg_add");
									Integer msg_port = jo.getInteger("msg_port");
									String msg_sendtime = jo.getString("msg_sendtime");
									String msg_format = jo.getString("msg_format");
									Integer msg_internal = jo.getInteger("msg_internal");
									String msg_text = jo.getString("msg_text");
									String msg_startnum = jo.getString("msg_startnum");
									String msg_count = jo.getString("msg_count");
									String msg_key = jo.getString("msg_key");
									sendMsg(msg_sendmethod, msg_add, msg_port, msg_sendtime, msg_format, msg_internal,msg_text, msg_startnum, msg_count, msg_key);
								}
						 });
						 threads.add(t);
						t.start();
					 }
					 for (Thread iThread : threads) {  
					      try {  
					        // 等待所有线程执行完毕  
					        iThread.join();  
					      } catch (InterruptedException e) {  
					        e.printStackTrace();  
					      }  
					} 
				}				
			}
		}	
	}
}
